package org.wangnian.idempotenttokendemo.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.wangnian.idempotenttokendemo.annotation.AutoIdempotent;
import org.wangnian.idempotenttokendemo.constants.Constant;
import org.wangnian.idempotenttokendemo.service.TokenService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
public class BusinessController {


    @Resource
    private TokenService tokenService;


    @PostMapping("/get/token")
    public String getToken() throws JsonProcessingException {
        String token = tokenService.createToken();
        if (StringUtils.isNotEmpty(token)) {
            Map<String,Object> map = new HashMap<>();
            map.put("code",Constant.CODE_SUCCESS);
            map.put("msg",Constant.CODE_SUCCESS);
            map.put("token",token);
            return new ObjectMapper().writeValueAsString(map);
        }
        return StringUtils.EMPTY;
    }


    @AutoIdempotent
    @PostMapping("/test/Idempotence")
    public String testIdempotence() {
        return "业务操作成功";
    }
}